<template>
<div id="userEdit">
    <div id="userEdit-header">
        <div id="leftBox">
            <el-button type="primary" @click="initFromData(); fromModel = 'add'; dialogVisible = true">
                <el-icon><CirclePlus /></el-icon>
                新增用户
            </el-button>
            <el-button type="primary" v-if="searchMode" @click="searchMode = false">
                <el-icon><ArrowRight /></el-icon>
                退出搜索模式
            </el-button>
        </div>
        <el-input placeholder="请输入内容" size="large" v-model="searchContent" class="input-with-select" @keyup.enter="searchUserInfo()" style="width: 520px;">
            <template #prepend>
                <el-select placeholder="请选择" v-model="searchKeyword" size="large" style="width: 100px; font-size: 12px;">
                    <el-option label="姓名" value="name"></el-option>
                    <el-option label="地址" value="address"></el-option>
                    <el-option label="邮箱" value="email"></el-option>
                    <el-option label="手机号码" value="phone"></el-option>
                </el-select>
            </template>
            <template #append>
                <el-button @click="searchUserInfo()">
                    <el-icon><Search /></el-icon>
                </el-button>
            </template>
        </el-input>
    </div>
    <div id="tableBox">
        <el-table
        :data="userData"
        style="width: calc(100% - 40px); margin: 0 auto;"
        height="100%">
            <el-table-column
            fixed="left"
            prop="name"
            label="姓名"
            width="100">
            </el-table-column>
            <el-table-column
            prop="sex"
            label="性别"
            width="60">
            </el-table-column>
            <el-table-column
            prop="address"
            label="地址"
            width="340">
            </el-table-column>
            <el-table-column
            prop="email"
            label="邮箱"
            width="260">
            </el-table-column>
            <el-table-column
            prop="phone"
            label="手机号码"
            width="120">
            </el-table-column>
            <el-table-column
            prop="createTime"
            label="上次登陆时间"
            width="160">
            </el-table-column>
            <el-table-column
            fixed="right"
            label="操作"
            min-width="160">
            <template #default="scope">
                <el-button
                @click="fromModel = 'edit'; userInfoEdit(scope.row)">编辑</el-button>
                <el-button
                type="danger"
                @click="delUserInfo(scope.row.id)">删除</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>
    <div id="paginationBox">
        <div>
            每页数量
            <el-select v-model="pageSize" style="width: 70px;" size="small">
                <el-option
                v-for="item in 9"
                :key="item"
                :label="(item+1)*5"
                :value="(item+1)*5">
                </el-option>
            </el-select>
            &nbsp;&nbsp;&nbsp;
            共 {{ total }} 条数据
        </div>
        <el-pagination 
            layout="prev, pager, next"
            background
            :page-size="pageSize"
            :total="total"
            @current-change="currentChange">
        </el-pagination>
    </div>

    <el-dialog
    :title="fromModel === 'add' ? '添加用户信息' : '编辑用户信息'"
    v-model="dialogVisible"
    @close="fromClose()"
    width="520px">
        <el-form ref="form" :model="fromData" :rules="fromRules" size="large" label-width="80px" style="width: calc(100% - 20px)">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="fromData.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select v-model="fromData.sex" placeholder="请选择性别">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="address">
                <el-input v-model="fromData.address" placeholder="请输入地址"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="fromData.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="fromData.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
        </el-form>
        <template #footer class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="fromConfirm()">确 定</el-button>
        </template>
    </el-dialog>
</div>
</template>

<script>
import UserApi from '../../../api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineComponent, reactive, toRefs, onBeforeMount, onMounted, getCurrentInstance, watch } from 'vue'
export default defineComponent({
    name: 'UserEdit',
    setup() {
        const { proxy } = getCurrentInstance()
        function fromClose() { // 表单组件关闭回调
            proxy.$refs['form'].resetFields()
        }
        function userDataFunc(s){ // 用户数据请求函数
            if(s && data.searchMode) return searchUserInfo(data.tempSearch)

            UserApi.UserEdit.userData({
                page: data.page,
                pageSize: data.pageSize
            }).then(res =>{
                data.userData = res.data
                data.total = res.total
            })
        }
        function currentChange(s){ // 分页切换函数
            data.page = s
            if(data.searchMode){
                data.tempSearch.page = s
            }
            data.userDataFunc(data.searchMode)
        }
        function initFromData(){ // 初始化表单数据函数
            data.fromData = {
                name:'',
                sex:'',
                address:'',
                email:'',
                phone:'',
            }
        }
        function fromConfirm(){ // 表单确定按钮点击事件
            proxy.$refs.form.validate((valid) => {
                if (valid) {
                    if(data.fromModel === 'add'){
                        data.addUSerInfo()
                    }else{
                        data.editUserInfo()
                    }

                    data.dialogVisible = false
                }
            });
        }
        function addUSerInfo(){ // 添加用户信息函数
            UserApi.UserEdit.addUserInfo(data.fromData).then(() =>{
                data.searchMode = false
                data.page = 1
                data.userDataFunc(data.searchMode)
                ElMessage({
                    message:'添加成功',
                    type:'success'
                });
            })
        }
        function userInfoEdit(data2){ // 用户信息编辑按钮点击事件
            data.fromData = JSON.parse(JSON.stringify(data2))

            data.dialogVisible = true
        }
        function editUserInfo(){ // 修改用户信息函数
            UserApi.UserEdit.editUserInfo(data.fromData).then(() =>{
                data.userDataFunc(data.searchMode)
                ElMessage({
                    message:'更改成功',
                    type:'success'
                });
            })
        }
        function delUserInfo(id){ // 删除用户信息函数
            ElMessageBox.confirm('确定删除该用户', '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            }).then(() => {
                UserApi.UserEdit.deltUserInfo({id}).then(() =>{
                    data.userDataFunc(this.searchMode)
                    ElMessage({
                        type: 'success',
                        message: '删除成功'
                    });
                })
            })
        }
        function searchUserInfo(obj){ // 搜索用户信息函数
            const obj2 = obj || JSON.parse(JSON.stringify({
                key: data.searchKeyword,
                value: data.searchContent,
                pageSize: data.pageSize,
                page: data.page
            }))

            if(obj2.value === '') return
            UserApi.UserEdit.searchUserInfo(obj2).then(res =>{
                if(res.data.length > 0){
                    if(!obj) data.tempSearch = JSON.parse(JSON.stringify(obj2))
                    data.searchMode = true

                    setTimeout(() => {
                        data.userData = res.data
                        data.total = res.total
                    }, 200);
                }else{
                    ElMessage({
                        message:'没有数据',
                        type:'warning',
                    })
                }
            })
        }

        const data = reactive({
            dialogVisible:false, // 用户数据编辑对话框是否展示
            userData: [], // 请求的用户数据
            total:0, // 用户数据总条数
            pageSize:15, // 每页用户数据的条数
            page:1, // 当前页面
            fromData:{}, // 表单数据
            fromModel:'add', // 表单模式
            fromRules: { // 表单验证规则
                name: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' },
                    { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
                ],
                sex: [
                    { required: true, message: '性别是必选的', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '地址不能为空', trigger: 'blur' },
                    { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮箱地址不能为空', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '手机号码不能为空', trigger: 'blur' },
                    { validator:(rule, value, callback) => {
                        const pattern = /0?(13|14|15|17|18|19)[0-9]{9}/
                        if (!pattern.test(value)) {
                            callback(new Error('请输入正确的手机号码'));
                        } else {
                            callback();
                        }
                    }, trigger: 'change' }
                ],
            },
            searchContent:'', // 搜索内容
            searchKeyword:'name', // 搜索关键字
            tempData:null, // 临时数据
            searchMode:false, // 是否处于搜索模式
            tempSearch:null, // 搜索临时数据

            fromClose,
            userDataFunc,
            currentChange,
            initFromData,
            fromConfirm,
            addUSerInfo,
            userInfoEdit,
            editUserInfo,
            delUserInfo,
            searchUserInfo
        })
        watch(()=>data.pageSize, ()=>{
            if(data.searchMode) data.tempSearch.pageSize = newval
            data.userDataFunc(data.searchMode)
        })
        watch(()=>data.searchMode, (newval)=>{
            if(newval){
                const obj = {
                    userData: data.userData,
                    pageSize: data.pageSize,
                    page: data.page,
                    total: data.total
                }

                data.tempData = JSON.parse(JSON.stringify(obj))
            }else{
                const obj = JSON.parse(JSON.stringify(data.tempData))

                data.userData = obj.userData
                data.pageSize = obj.pageSize
                data.page = obj.page
                data.total = obj.total

                data.tempData = null
            }
        })

        onBeforeMount(() => {
            userDataFunc()
        })
        onMounted(() => {
            // 组件挂载到页面之后执行
        })
        return {
            ...toRefs(data),
        }
    },
})
</script>

<style scoped>
#userEdit{
    width: 100%;
    height: 100%;
}
#userEdit-header{
    height: 50px;
    padding: 0 20px 10px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
#tableBox{
    height: calc(100% - 120px);
}
#paginationBox{
    height: 60px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #cfd2d9;
    font-size: 14px;
    padding: 0 10px 0 20px;
}
</style>